<!DOCTYPE html>

<head xmlns:color="http://www.w3.org/1999/xhtml">
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <script src="../../../js/vue.js"></script>
    <script type="text/javascript" src="../../../js/jquery-2.1.4.js"></script>
    <link rel="stylesheet" href="../../../layuiadmin/layui/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
<!--普通div组获取复选框数据-->
<!--<div class="layui-btn-group demoTable">-->
<!--<button class="layui-btn" data-type="getCheckData">获取选中行数据</button>-->
<!--<button class="layui-btn" data-type="getCheckLength">获取选中数目</button>-->
<!--<button class="layui-btn" data-type="isAll">验证是否全选</button>-->
<!--</div>-->

<!--头部工具条-->
<script type="text/html" id="headbar">
    <div class="layui-btn-container"  >
        <!--使用表达式让按钮动态显示，if条件为true则显示，false不显示-->
        {{#  if(insert){ }}
        <button type="button" class="layui-btn" lay-event="insert">
            <i class="layui-icon">&#xe654;</i> 新增
        </button>
        {{#  } }}
        {{#  if(del){ }}
        <button class="layui-btn layui-btn-danger" lay-event="getCheckData">
            <i class="layui-icon">&#xe640;</i>批量删除
        </button>
        {{#  } }}
    </div>
</script>
<!-- 每一行工具条 -->
<script type="text/html" id="barDemo">
    {{#  if(update){ }}
    <button type="button" class="layui-btn layui-btn-xs layui-btn-radius layui-btn-warm" lay-event="singleUpdate">
        <i class="layui-icon">&#xe642;</i> 修改
    </button>
    {{#  } }}

    {{#  if(del){ }}
    <button type="button" class="layui-btn layui-btn-xs layui-btn-radius layui-btn-danger" lay-event="singleDel">
        <i class="layui-icon">&#xe640;</i> 删除
    </button>
    {{#  } }}
</script>
<!--头部工具条获取复选框数据-->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
    </div>
</script>
<!---------------------------------------------条件搜索框------------------------------------------->
<div class="demoTable" style="margin-top: 10px;margin-left: 10px">
    <form id="serachForm" class="layui-form">
        商品名：
        <div class="layui-inline" style="width: 100px">
            <input class="layui-input" name="name" id="searchName" autocomplete="off">
        </div>
        商品编号：
        <div class="layui-inline" >
            <input class="layui-input" id="scode" name="proCode" autocomplete="off">
        </div>

        <div class="layui-inline" style="width: 200px;">
            <label class="layui-form-label">上架状态</label>
            <div class="layui-input-block">
                <select name="status" id="status" lay-filter="aihao">
                    <option value="" selected>全部</option>
                    <option value="1">上架</option>
                    <option value="0">下架</option>
                </select>
            </div>
        </div>

        <div class="layui-inline" style="width: 250px;">
            <label class="layui-form-label">品牌</label>
            <div class="layui-input-block">
                <select  name="businessName" id="businessName">
                    <option value="" selected>所有品牌</option>

                </select>
            </div>
        </div>
        <div class="layui-inline" style="width: 250px;">
            <label class="layui-form-label">类型</label>
            <div class="layui-input-block">
                <select  name="proType" id="proType">
                    <option value="" selected>所有类型</option>

                </select>
            </div>
        </div>
        <div class="layui-inline" style="margin-left: 10px">
            <!--这个地方的不能直接使用button标签，使用button标签会重复提交数据-->
            <input type="button" class="layui-btn" data-type="reload" value="搜索">
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>

    </form>
</div>
<!-----------------------------------------表格内容--------------------------------------------->
<div id="content">
    <table class="layui-table"
           lay-data="{url:'/houtai/products/getProducts',page:true,limit:10,limits:[10,20,10000],toolbar:'#headbar',
                     height:'full-100',totalRow:true,loading:true,title:'商品信息表',
                     //把返回的数据result转为换layUI需要的格式，此处返回的是mybatisPlus的IPage对象，具体返回值自己设定
                     parseData: function(res){ //res 即为原始返回的数据
                        console.log('这是表格数据');
                        console.log(res);
                        return {
                            'code': res.code, //解析接口状态
                            'msg': res.message, //解析提示文本
                            'count': res.obj.totalSize, //解析数据长度
                            'data': res.li //解析数据列表
                          };
                       },
                //给表格设置一个ID
               id:'test'}"
           lay-filter="filter">
        <thead>
        <tr>
            <th lay-data="{checkbox:true}"></th><!--开起全选框-->
            <th lay-data="{field:'productId', sort: true,hide:true}">商品ID</th><!--field：实体类属性，sort：排序-->
            <th lay-data="{field:'productName'}">商品名</th>
            <th lay-data="{field:'productDesc', sort: true,hide:true}">商品描述</th>
            <th lay-data="{field:'business',
                templet:function (d) {
                    return d.business.businessName;
                }
            }">品牌名</th>

            <th lay-data="{field:'productPrice',templet:function(d){
                return Number(d.productPrice).toFixed(2);
            }}">单价</th>
            <th lay-data="{field:'productImg',templet:'#imgTpl'}">商品图片</th>
            <th lay-data="{field:'promotionPrice',hide:true,templet:function(d){
                return Number(d.promotionPrice).toFixed(2);
            }}">促销价</th>
            <th lay-data="{field:'productNum'}">库存</th>
            <th lay-data="{field:'productCode'}">商品编号</th>

            <th lay-data="{field:'producttype',templet:function (d) {
                    return d.producttype.producttypeName;
                }}">类型</th>
            <th lay-data="{field:'productIshot',templet:'#productIshot'}">是否热卖</th>
            <th lay-data="{field:'productStatus',templet:'#proStatus'}">是否在售</th>
            <!--最后一列操作列，有修改或删除的权限就显示这列，否者不显示，通过Vue实现-->
            <th v-if="isShow" lay-data="{field:'opeartion', toolbar: '#barDemo',width : 170}">操作</th>

        </tr>
        </thead>
    </table>
</div>

 <script type="text/html" id="proStatus">
              {{#  if(d.productStatus === 1){ }}
                 <span class="layui-badge layui-bg-green">在售</span>
              {{#  } else { }}
               <span class="layui-badge">已下架</span>
              {{#  } }}
</script>
<script type="text/html" id="productIshot">
              {{#  if(d.productIshot == '1'){ }}
                 <span class="layui-badge layui-bg-green">是</span>
              {{#  } else { }}
               <span class="layui-badge">否</span>
              {{#  } }}
</script>
<script src="../../../layuiadmin/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<!--动态显示图片-->
<script type="text/html" id="imgTpl">
    <ul>
        <img style="width: 30px;height: 30px" onclick="showBigImage(this)" src="{{d.productImg}}" >
    </ul>
</script>

<script>
    var insert = false;
    var del= false;
    var update= false;
    var isShow=false;
    $(function () {
        // insert = true;
        // del = true;
        // update = true;
    });
    //利用Vue判断是否具备每一行的删除或者修改权限
    var vue = new Vue({
        el:"#content",
        data:{
            user:"",
            buttons:[],
            allBusiness:[],
            allProTypes:[]
        },
        beforeCreate:function(){
            var _this = this;
            $.ajax({
                url : "/houtai/page/products/product/getAllBusiness",
                type : "get",
                dataType : "json",
                async: false,
                success : function(data) {
                    console.log("这是business。。。。。。。");
                    console.log(data);
                    _this.allBusiness = data.li;
                    //console.log("_this.allBusiness:"+JSON.stringify(_this.allBusiness));
                    for (var i=0;i<data.li.length;i++ ) {
                        $("#businessName").append("<option  value="+data.li[i].businessName+">"+data.li[i].businessName+"</option>");
                    }
                }
            });
            $.ajax({
                url : "/houtai/page/products/product/getAllProTypes",
                type : "get",
                dataType : "json",
                async: false,
                success : function(data) {
                    for (var i=0;i<data.li.length;i++ ) {
                        $("#proType").append("<option  value="+data.li[i].producttypeName+">"+data.li[i].producttypeName+"</option>");
                    }
                }
            });
        },
        created:function(){

            $.ajax({
                url : "/houtai/page/products/product/list",
                type : "get",
                dataType : "json",

                success : function(data) {
                    if(data.message=="success"){

                    }else if(data.message == "premissionException"){
                        location.href = "/houtai/page/exception/NoPremission.html";
                    }else{
                        location.href = "/houtai/page/exception/500.html";
                    }
                }
            });

        },

        methods: {

        },
        computed:{
            isShow:function () {
                var _this = this;
                var delbtn=false;
                var updatebtn=false;
                //获取当前网页地址
                var url = location.pathname;
                $.ajax({
                    url: "/houtai/adminuser/buttons",
                    type: "get",
                    async: false,
                    data: {
                        url: url
                    },
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        _this.buttons = data.li;
                        // console.log(insert);
                        for(var i=0;i<_this.buttons.length;i++){

                            if(_this.buttons[i].menuUrl.indexOf("insert")!=-1){

                                //insert = true;

                                break;
                            }
                        }
                        for(var i=0;i<_this.buttons.length;i++){
                            if(_this.buttons[i].menuUrl.indexOf("delete")!=-1){
                                del = true;
                                isShow = true;
                                delbtn = true;
                                break;
                            }
                        }
                        for(var i=0;i<_this.buttons.length;i++){
                            if(_this.buttons[i].menuUrl.indexOf("update")!=-1){
                                update = true;
                                isShow = true;
                                updatebtn =  true;
                                break;
                            }
                        }

                    }
                });
                console.log("---------");
                console.log(delbtn);
                console.log(updatebtn);

                if(delbtn||updatebtn){
                    return true;
                }else{
                    return false;
                }

            }
        }

    })
    //点击图片放大
    function showBigImage(e) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true, //点击阴影关闭
            area: [$(e).width + 'px', $(e).height + 'px'], //宽高
            content: "<img src=" + $(e).attr('src') + " />"
        });
    };
    layui.use(['table','jquery','laypage','layer'], function(){
        var table = layui.table;
        var $ = layui.jquery;
        var layer = layui.layer;




        //监听顶部工具栏事件
        table.on('toolbar(filter)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;

                switch(obj.event){
                    //点击批量删除执行以下代码
                    case 'getCheckData':
                        if(data.length < 1){
                            layer.msg("至少选择一行哦!!!");
                        }else{
                        layer.confirm('真的删除行么', function(index){
                            layer.close(index);

                            var productIds = new Array();
                            for(var i = 0;i < data.length;i++){
                                productIds.push(data[i].productId);
                            }

                            var s = JSON.stringify(productIds);
                            console.log(s);
                            $.ajax({
                                url:"/houtai/page/products/product/delete",
                                data:{productIds:s},
                                type:"post",
                                dataType:"json",
                                success:function (data) {
                                    if(data.message == "success"){
                                        layer.msg("删除成功",{icon: 6});
                                        //重载表格
                                        $(".layui-laypage-btn").click();
                                    }else if(data.message == "premissionException"){
                                        location.href = "/houtai/page/exception/NoPremission.html";
                                    }else if(data.message == "serverException"){
                                        location.href = "/houtai/page/exception/500.html";
                                    }else{
                                        layer.msg("删除失败", {icon: 5});
                                    }
                                }
                            })
                        });
                };
                        break;
            }

        });
        //监听每一行工具条
        table.on('tool(filter)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            console.log(data);
            if(layEvent === 'detail'){//查看
                //do somehing
            } else if(layEvent === 'singleDel'){ //删除
                layer.confirm('真的删除行么', function(index){
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url:"/houtai/page/products/product/delete",
                        data:{productIds: data.productId},
                        type:"post",
                        dataType:"json",
                        success:function (data) {
                            if(data.message == "success"){
                                layer.msg("删除成功",{icon: 6});
                                //重载表格
                                $(".layui-laypage-btn").click();
                            }else if(data.message == "premissionException"){
                                location.href = "/houtai/page/exception/NoPremission.html";
                            }else if(data.message == "serverException"){
                                location.href = "/houtai/page/exception/500.html";
                            }else{
                                layer.msg("删除失败", {icon: 5});
                            }
                        }
                    })
                });
            } else if(layEvent === 'singleUpdate'){ //编辑
                $.ajax({
                    url:"/houtai/page/products/product/update",
                    data:{productId:data.productId},
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        if(data.message == "success"){
                            location.href = "update.html";
                        }else if(data.message == "premissionException"){
                            location.href = "/houtai/page/exception/NoPremission.html";
                        }else {
                            location.href = "/houtai/page/exception/500.html";
                        }
                    }
                })
            }
        });



        //设置搜索框查询条件
        var $ = layui.$, active = {
            reload: function(){
                var demoReload = $('#demoReload');
                var str = $("#serachForm").serialize();
                //执行重载
                table.reload('test', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        name:$("#searchName").val(),
                        proCode:$("#scode").val(),
                        status:$("#status").val(),
                        businessName:$("#businessName").val(),
                        proType:$("#proType").val()
                    }
                }, 'data');
            }
        };

        //监听搜索框提交按钮
        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });

</script>

</body>
</html>